package org.gitos.cloud.server.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.gitos.cloud.domain.server.Inuser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hc on 2016/3/30 0030.
 * app消息推送
 */
@Component
public class PushToAppService {
    private static Logger log = LoggerFactory.getLogger(PushToAppService.class);

    public final static int CLOSE = 0;
    public final static int OPEN = 1;

    private final static int ANDROID = 1;
    private final static int IOS = 2;

    private final static String SERVER = "http://msg.umeng.com/api/send";

    @Value("${app_pusher.ios_appkey}")
    private String ios_appkey;
    @Value("${app_pusher.ios_secret}")
    private String ios_secret;
    @Value("${app_pusher.android_appkey}")
    private String android_appkey;
    @Value("${app_pusher.android_secret}")
    private String android_secret;
    @Autowired
    private RelationService relationService;

    /*  必填 消息发送类型,其值可以为:
     unicast-单播
     listcast-列播(要求不超过500个device_token)
     filecast-文件播
             (多个device_token可通过文件形式批量发送）
                     broadcast-广播
                     groupcast-组播
                     (按照filter条件筛选特定用户群, 具体请参照filter参数)
     customizedcast(通过开发者自有的alias进行推送),
     包括以下两种case:
             - alias: 对单个或者多个alias进行推送
     - file_id: 将alias存放到文件后，根据file_id来推送*/
    private final static String PUSH_TYPE = "listcast";
    /*    必填 消息类型，值可以为:
       notification-通知，message-消息*/
    private final static String DISPLAY_TYPE = "message";

    public boolean push(String mac, int state) {
        List<Inuser> inusers = relationService.findInusersByMac(mac);
        if (inusers.size() > 500 || inusers.size() == 0) {
            return false;
        }
        StringBuffer androids = new StringBuffer();
        StringBuffer ios = new StringBuffer();
        for (Inuser inuser : inusers) {
            if (inuser.getMobile_os() == ANDROID) {
                androids.append(",").append(inuser.getInuser_token());
            } else if (inuser.getMobile_os() == IOS) {
                ios.append(",").append(inuser.getInuser_token());
            }
        }
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("timestamp", timestamp);
        map.put("type", PUSH_TYPE);
        String android_mobile = androids.toString().replaceFirst(",", "");
        String ios_mobile = ios.toString().replaceFirst(",", "");
        if (android_mobile.length() > 0) {
            map.put("appkey", android_appkey);
            map.put("device_tokens", android_mobile);
            map.put("payload", JSONObject.parse("{'display_type':'" + DISPLAY_TYPE + "','body':{'custom':{'mac':'" + mac + "','state':'" + state + "'}}}"));
            start(map, android_secret);
        }
        if (ios_mobile.length() > 0) {
            map.put("appkey", ios_appkey);
            map.put("device_tokens", ios_mobile);
            map.put("payload", JSONObject.parse("{'aps':{'alert':{'mac':'" + mac + "','state':'" + state + "'}}}"));
            start(map, ios_secret);
        }
        return true;
    }

    private boolean start(HashMap<String, Object> map, String secret) {
        String post_body = JSONObject.toJSONString(map);
        String sign = null;
        try {
            sign = DigestUtils.md5DigestAsHex(("POST" + SERVER + post_body + secret).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringEntity entity = new StringEntity(JSONObject.toJSONString(map), "UTF-8");
        String url = SERVER + "?sign=" + sign;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        StringBuffer result = new StringBuffer();
        try {
            HttpResponse response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        log.info("pushToApp【device_tokens:" + map.get("device_tokens") + "】");
        log.info("response: " + result);
        JSONObject jsonObject = JSONObject.parseObject(result.toString());
        return !(jsonObject == null || "fail".equalsIgnoreCase(jsonObject.getString("ret")));
    }

}
